package com.ruoyi.basebill.task;

import com.ruoyi.basebill.domain.OmsPurinwarehsbill;
import com.ruoyi.basebill.domain.OmsPurinwarehsbillentry;
import com.ruoyi.basebill.domain.OmsSaleissuebill;
import com.ruoyi.basebill.domain.OmsSaleissuebillentry;
import com.ruoyi.basebill.mapper.OmsPurinwarehsbillMapper;
import com.ruoyi.basebill.mapper.OmsSaleissuebillMapper;
import com.ruoyi.basebill.service.impl.OmsPurinwarehsbillServiceImpl;
import com.ruoyi.basebill.service.impl.OmsSaleissuebillServiceImpl;
import com.ruoyi.basebill.task.util.OmsTaskUtil;
import com.ruoyi.basedata.domain.BdMaterial;
import com.ruoyi.basedata.domain.BdMaterialconfig;
import com.ruoyi.basedata.service.IBdMaterialService;
import com.ruoyi.basedata.service.impl.BdMaterialconfigServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/*
 * @Author ptt
 * @Date 2024/12/11
 * @Description 将一级组织间交易的销出采入进行拆单
 *
 */
@Component("DismantlingBillTask")
public class DismantlingBillTask {

    @Autowired
    private OmsSaleissuebillServiceImpl saleissuebillService;

    @Autowired
    private OmsSaleissuebillMapper omsSaleissuebillMapper;

    @Autowired
    private OmsPurinwarehsbillServiceImpl purinwarehsbillService;

    @Autowired
    private OmsPurinwarehsbillMapper omsPurinwarehsbillMapper;

    @Autowired
    private BdMaterialconfigServiceImpl bdMaterialconfigService;

    @Autowired
    private IBdMaterialService bdMaterialService;

    @Autowired
    private OmsTaskUtil omsTaskUtil;


    public void disBill(){
        disSaleIssueBill();
        disPurInWarehsBill();
    }

    /**
     * 查出符合条件的所有销出单，拆解成采入红字
     * 销售：入库送货客户，排除库存组织
     */
    @Transactional
    public void disSaleIssueBill(){
        List<OmsSaleissuebill> omsSaleissuebills = saleissuebillService.selectSumBillNumberIsNull();
        //如果集合不为null且不为空
        //遍历集合，将id存储在hashset中，用于后续进行批量查询。
        HashSet<Long> idSet = new HashSet<Long>();
        HashMap<Long, OmsSaleissuebill> saleMap = new HashMap<Long, OmsSaleissuebill>();
        if(omsSaleissuebills!=null&& !omsSaleissuebills.isEmpty()) {
            for (int i = 0; i < omsSaleissuebills.size(); i++) {
                OmsSaleissuebill omsSaleissuebill = omsSaleissuebills.get(i);
                Long id = omsSaleissuebill.getId();
                idSet.add(id);
            }
            //根据id集合进行批量查询
            List<OmsSaleissuebill> omsSaleissuebillsList = saleissuebillService.selectOmsSaleissuebillByIds(idSet);
            //循环集合，将数据存储在map中，用于后续快速获取。
            if(omsSaleissuebillsList!=null&& !omsSaleissuebillsList.isEmpty()) {
                for (int i = 0; i < omsSaleissuebillsList.size(); i++) {
                    OmsSaleissuebill omsSaleissuebill = omsSaleissuebillsList.get(i);
                    Long id = omsSaleissuebill.getId();
                    saleMap.put(id, omsSaleissuebill);
                }
            }
        }
        for (int i = 0; omsSaleissuebills!=null && i < omsSaleissuebills.size(); i++) {
            OmsSaleissuebill omsSaleissuebill = omsSaleissuebills.get(i);
            String isdis = omsSaleissuebill.getIsdis();
            if (StringUtils.isNotBlank(isdis)) continue;
            omsSaleissuebill = saleMap.get(omsSaleissuebill.getId());
            List<OmsSaleissuebillentry> omsSaleissuebillentryList = omsSaleissuebill.getOmsSaleissuebillentryList();
            if(omsSaleissuebillentryList==null||omsSaleissuebillentryList.size()==0) continue;
            String storageorgnumber = omsSaleissuebill.getCustomernumber();
            String suppliernumber = omsSaleissuebill.getStorageorgnumber();
            BdMaterialconfig bdMaterialconfig = new BdMaterialconfig();
            bdMaterialconfig.setReceiptorg(""+storageorgnumber+"");
            bdMaterialconfig.setExcludeorg(""+suppliernumber+"");
            bdMaterialconfig.setState("1");
            List<BdMaterialconfig> bdMaterialconfigs = bdMaterialconfigService.selectBdMaterialconfigList2(bdMaterialconfig);
            if (bdMaterialconfigs==null||bdMaterialconfigs.size()==0)  continue;
            HashMap<String, String> hashMapConfig = getBdMaterialConfigInfo(bdMaterialconfigs);
            //新集合，把符合条件的数据放入集合中
            List<OmsPurinwarehsbillentry> newList = new ArrayList<OmsPurinwarehsbillentry>();
            for (int i1 = omsSaleissuebillentryList.size()-1 ; i1 >= 0 ; i1--) {
                OmsSaleissuebillentry omsSaleissuebillentry = omsSaleissuebillentryList.get(i1);
                String materialnumber = omsSaleissuebillentry.getMaterialnumber();
                BdMaterial bdMaterial = bdMaterialService.selectBdMaterialByNumber(materialnumber);
                if(bdMaterial==null) continue;
                boolean isDis = false;
                if(hashMapConfig.containsKey("oneGroup")&&hashMapConfig.get("oneGroup").contains("'"+bdMaterial.getGroup1number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("twoGroup")&&hashMapConfig.get("twoGroup").contains("'"+bdMaterial.getGroup2number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("threeGroup")&&hashMapConfig.get("threeGroup").contains("'"+bdMaterial.getGroup3number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("fourGroup")&&hashMapConfig.get("fourGroup").contains("'"+bdMaterial.getGroup4number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("material")&&hashMapConfig.get("material").contains("'"+bdMaterial.getMaterialnumber()+"'")) isDis = true;
                if(!isDis) continue;
                OmsPurinwarehsbillentry omsPurinwarehsbillentry = salEntryChangePurEntry(omsSaleissuebillentry);
                newList.add(omsPurinwarehsbillentry);
                omsSaleissuebillentryList.remove(i1);
            }
            if(newList.size()==0){
                continue;
            }
            OmsPurinwarehsbill omsPurinwarehsbill = salBillChangePurBill(omsSaleissuebill);
            omsPurinwarehsbill.setOmsPurinwarehsbillentryList(newList);
            omsPurinwarehsbill.setIsdis("被拆新单");
            purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
            omsSaleissuebill = saleMap.get(omsSaleissuebill.getId());
            omsSaleissuebill.setOmsSaleissuebillentryList(omsSaleissuebillentryList);
            omsSaleissuebillMapper.deleteOmsSaleissuebillentryByParentid(omsSaleissuebill.getId());
            saleissuebillService.insertOmsSaleissuebillentry(omsSaleissuebill);
            if(omsSaleissuebillentryList.size()==0){
                omsSaleissuebill.setIssum(1L);
                omsSaleissuebill.setSumbillnumber("分录为空无需汇总");
            }
            omsSaleissuebillMapper.updateOmsSaleissuebill(omsSaleissuebill);
        }
    }

    /**
     * 查出符合条件的所有采入单，拆解成销出红字
     * 采购：入库库存组织，排除供应商
     */
    @Transactional
    public void disPurInWarehsBill(){
        List<OmsPurinwarehsbill> omsPurinwarehsbills = purinwarehsbillService.selectSumBillNumberIsNull();
        //如果集合不为null且不为空
        //遍历集合，将id存储在hashset中，用于后续进行批量查询。
        HashSet<Long> idSet = new HashSet<Long>();
        HashMap<Long, OmsPurinwarehsbill> purMap = new HashMap<Long, OmsPurinwarehsbill>();
        if(omsPurinwarehsbills!=null&& !omsPurinwarehsbills.isEmpty()) {
            for (int i = 0; i < omsPurinwarehsbills.size(); i++) {
                OmsPurinwarehsbill omsPurinwarehsbill = omsPurinwarehsbills.get(i);
                Long id = omsPurinwarehsbill.getId();
                idSet.add(id);
            }
            //根据id集合进行批量查询
            List<OmsPurinwarehsbill> omsPurinwarehsbillsList = purinwarehsbillService.selectOmsPurinwarehsbillByIds(idSet);
            //循环集合，将数据存储在map中，用于后续快速获取。
            if(omsPurinwarehsbillsList!=null&& !omsPurinwarehsbillsList.isEmpty()) {
                for (int i = 0; i < omsPurinwarehsbillsList.size(); i++) {
                    OmsPurinwarehsbill omsPurinwarehsbill = omsPurinwarehsbillsList.get(i);
                    Long id = omsPurinwarehsbill.getId();
                    purMap.put(id, omsPurinwarehsbill);
                }
            }
        }
        for (int i = 0; omsPurinwarehsbills!=null && i < omsPurinwarehsbills.size(); i++) {
            OmsPurinwarehsbill omsPurinwarehsbill = omsPurinwarehsbills.get(i);
            String isdis = omsPurinwarehsbill.getIsdis();
            if (StringUtils.isNotBlank(isdis)) continue;
            omsPurinwarehsbill = purMap.get(omsPurinwarehsbill.getId());
            List<OmsPurinwarehsbillentry> omsPurinwarehsbillentryList = omsPurinwarehsbill.getOmsPurinwarehsbillentryList();
            if(omsPurinwarehsbillentryList==null||omsPurinwarehsbillentryList.size()==0) continue;
            String storageorgnumber = omsPurinwarehsbill.getStorageorgnumber();
            String suppliernumber = omsPurinwarehsbill.getSuppliernumber();
            BdMaterialconfig bdMaterialconfig = new BdMaterialconfig();
            bdMaterialconfig.setReceiptorg(""+storageorgnumber+"");
            bdMaterialconfig.setExcludeorg(""+suppliernumber+"");
            bdMaterialconfig.setState("1");
            List<BdMaterialconfig> bdMaterialconfigs = bdMaterialconfigService.selectBdMaterialconfigList2(bdMaterialconfig);
            if (bdMaterialconfigs==null||bdMaterialconfigs.size()==0)  continue;
            HashMap<String, String> hashMapConfig = getBdMaterialConfigInfo(bdMaterialconfigs);
            //新集合，把符合条件的数据放入集合中
            List<OmsSaleissuebillentry> newList = new ArrayList<OmsSaleissuebillentry>();
            for (int i1 = omsPurinwarehsbillentryList.size()-1 ; i1 >= 0 ; i1--) {
                OmsPurinwarehsbillentry omsPurinwarehsbillentry = omsPurinwarehsbillentryList.get(i1);
                String materialnumber = omsPurinwarehsbillentry.getMaterialnumber();
                BdMaterial bdMaterial = bdMaterialService.selectBdMaterialByNumber(materialnumber);
                if(bdMaterial==null) continue;
                boolean isDis = false;
                if(hashMapConfig.containsKey("oneGroup")&&hashMapConfig.get("oneGroup").contains("'"+bdMaterial.getGroup1number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("twoGroup")&&hashMapConfig.get("twoGroup").contains("'"+bdMaterial.getGroup2number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("threeGroup")&&hashMapConfig.get("threeGroup").contains("'"+bdMaterial.getGroup3number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("fourGroup")&&hashMapConfig.get("fourGroup").contains("'"+bdMaterial.getGroup4number()+"'")) isDis = true;
                if(hashMapConfig.containsKey("material")&&hashMapConfig.get("material").contains("'"+bdMaterial.getMaterialnumber()+"'")) isDis = true;
                if(!isDis) continue;
                OmsSaleissuebillentry omsSaleissuebillentry = purEntryChangeSalEntry(omsPurinwarehsbillentry);
                newList.add(omsSaleissuebillentry);
                omsPurinwarehsbillentryList.remove(i1);
            }
            if(newList.size()==0){
                continue;
            }
            OmsSaleissuebill omsSaleissuebill = purBillChangeSalBill(omsPurinwarehsbill);
            omsSaleissuebill.setIsdis("被拆新单");
            omsSaleissuebill.setOmsSaleissuebillentryList(newList);
            saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
            omsPurinwarehsbill = purMap.get(omsPurinwarehsbill.getId());
            omsPurinwarehsbill.setOmsPurinwarehsbillentryList(omsPurinwarehsbillentryList);
            omsPurinwarehsbillMapper.deleteOmsPurinwarehsbillentryByParentid(omsPurinwarehsbill.getId());
            purinwarehsbillService.insertOmsPurinwarehsbillentry(omsPurinwarehsbill);
            if(omsPurinwarehsbillentryList.size()==0){
                omsPurinwarehsbill.setIssum(1L);
                omsPurinwarehsbill.setSumbillnumber("分录为空无需汇总");
            }
            omsPurinwarehsbillMapper.updateOmsPurinwarehsbill(omsPurinwarehsbill);
        }
    }

    /**
     * 根据传入的物料配置表集合，获取对应的物料组号，返回一个map集合
     * @param bdMaterialconfigs
     * @return
     */
    public HashMap<String,String> getBdMaterialConfigInfo(List<BdMaterialconfig> bdMaterialconfigs){
        StringBuilder stringBuilder1 = new StringBuilder();
        StringBuilder stringBuilder2 = new StringBuilder();
        StringBuilder stringBuilder3 = new StringBuilder();
        StringBuilder stringBuilder4 = new StringBuilder();
        StringBuilder stringBuilder5 = new StringBuilder();
        for (int i2 = 0; i2 < bdMaterialconfigs.size(); i2++) {
            BdMaterialconfig bdMaterialconfig1 = bdMaterialconfigs.get(i2);
            if("oneGroup".equals(bdMaterialconfig1.getMaterialgroup())){
                stringBuilder1.append("'"+bdMaterialconfig1.getMaterialnumber()+"',");
                continue;
            }
            if("twoGroup".equals(bdMaterialconfig1.getMaterialgroup())){
                stringBuilder2.append("'"+bdMaterialconfig1.getMaterialnumber()+"',");
                continue;
            }
            if("threeGroup".equals(bdMaterialconfig1.getMaterialgroup())){
                stringBuilder3.append("'"+bdMaterialconfig1.getMaterialnumber()+"',");
                continue;
            }
            if("fourGroup".equals(bdMaterialconfig1.getMaterialgroup())){
                stringBuilder4.append("'"+bdMaterialconfig1.getMaterialnumber()+"',");
                continue;
            }
            if("material".equals(bdMaterialconfig1.getMaterialgroup())){
                stringBuilder5.append("'"+bdMaterialconfig1.getMaterialnumber()+"',");
                continue;
            }
        }
        HashMap<String, String> hashMap = new HashMap<>();
        if(stringBuilder1.length()!=0){
            String substring = "("+stringBuilder1.substring(0, stringBuilder1.length() - 1)+")";
            hashMap.put("oneGroup", substring);
        }
        if(stringBuilder2.length()!=0){
            String substring = "("+stringBuilder2.substring(0, stringBuilder2.length() - 1)+")";
            hashMap.put("twoGroup", substring);
        }
        if(stringBuilder3.length()!=0){
            String substring = "("+stringBuilder3.substring(0, stringBuilder3.length() - 1)+")";
            hashMap.put("threeGroup", substring);
        }
        if(stringBuilder4.length()!=0){
            String substring = "("+stringBuilder4.substring(0, stringBuilder4.length() - 1)+")";
            hashMap.put("fourGroup", substring);
        }
        if(stringBuilder5.length()!=0){
            String substring = "("+stringBuilder5.substring(0, stringBuilder5.length() - 1)+")";
            hashMap.put("material", substring);
        }
        return hashMap;
    }

    public OmsPurinwarehsbillentry salEntryChangePurEntry(OmsSaleissuebillentry salEntry){
        OmsPurinwarehsbillentry purentry = new OmsPurinwarehsbillentry();
        purentry.setWarehousenumber(salEntry.getWarehousenumber());
        purentry.setWarehousename(salEntry.getWarehousename());
        purentry.setMaterialnumber(salEntry.getMaterialnumber());
        purentry.setMaterialname(salEntry.getMaterialname());
        purentry.setUnitnumber(salEntry.getUnitnumber());
        purentry.setBaseunitnumber(salEntry.getBaseunitnumber());
        purentry.setQty(salEntry.getQty().multiply(new BigDecimal(-1)));
        purentry.setBaseqty(salEntry.getBaseqty().multiply(new BigDecimal(-1)));
        purentry.setPrice(salEntry.getPrice());
        purentry.setTaxrate(salEntry.getTaxrate());
        purentry.setTaxprice(salEntry.getTaxprice());
        purentry.setAmount(salEntry.getAmount().multiply(new BigDecimal(-1)));
        purentry.setTax(salEntry.getTax().multiply(new BigDecimal(-1)));
        purentry.setTaxamount(salEntry.getTaxamount().multiply(new BigDecimal(-1)));
        purentry.setRemark(salEntry.getRemark());
        purentry.setIspresent(salEntry.getIspresent());
        return purentry;
    }
    public OmsPurinwarehsbill salBillChangePurBill(OmsSaleissuebill sal1){
        OmsPurinwarehsbill pur1 = new OmsPurinwarehsbill();
        pur1.setBizdate(sal1.getBizdate());
        String billNumber = omsTaskUtil.setBillNumber(pur1);
        pur1.setBillnumber(billNumber);
        //库存组织
        pur1.setStorageorgnumber(sal1.getStorageorgnumber());
        pur1.setStorageorgname(sal1.getStorageorgname());
        //设置送货客户
        pur1.setSuppliernumber(sal1.getCustomernumber());
        pur1.setSuppliername(sal1.getCustomername());
        //业务类型
        if("210".equals(sal1.getBiztypenumber())){
            pur1.setBiztypenumber("111");
            pur1.setBiztypename("普通采购退货");
        }else if("211".equals(sal1.getBiztypenumber())){
            pur1.setBiztypenumber("110");
            pur1.setBiztypename("普通采购");
        }
        //事务类型
        if("012".equals(sal1.getTransactiontypenumber())){
            pur1.setTransactiontypenumber("005");
            pur1.setTransactiontypename("成本入库退货");
        }else if("013".equals(sal1.getTransactiontypenumber())){
            pur1.setTransactiontypenumber("004");
            pur1.setTransactiontypename("成本入库");
        }
        //记账公司
        pur1.setAccountcompanynumber(sal1.getAccountcompanynumber());
        pur1.setAccountcompanyname(sal1.getAccountcompanyname());
        //成本中心
        pur1.setCostcenternumber(sal1.getCostcenternumber());
        pur1.setCostcentername(sal1.getCostcentername());
        //币别
        pur1.setCurrency(sal1.getCurrency());
        //汇率
        pur1.setExchangerate(sal1.getExchangerate());
        //厂编
//        sal.setFactorymake(pur);
        //来源单据
        pur1.setSrcbilltype(sal1.getSrcbilltype());
        pur1.setSrcbillnumber(sal1.getSrcbillnumber());
        //备注
        pur1.setDescription(sal1.getDescription());
        //创建时间
        pur1.setCreatetime(new Date());
        //是否外部客户
//        pur1.setIsoutcustomer(0L);
        //来源系统
        pur1.setSrcsys(sal1.getSrcsys());
        return pur1;
    }

    public OmsSaleissuebillentry purEntryChangeSalEntry(OmsPurinwarehsbillentry purentry){
        OmsSaleissuebillentry sqlentry = new OmsSaleissuebillentry();
        sqlentry.setWarehousenumber(purentry.getWarehousenumber());
        sqlentry.setWarehousename(purentry.getWarehousename());
        sqlentry.setMaterialnumber(purentry.getMaterialnumber());
        sqlentry.setMaterialname(purentry.getMaterialname());
        sqlentry.setUnitnumber(purentry.getUnitnumber());
        sqlentry.setBaseunitnumber(purentry.getBaseunitnumber());
        sqlentry.setQty(purentry.getQty().multiply(new BigDecimal(-1)));
        sqlentry.setBaseqty(purentry.getBaseqty().multiply(new BigDecimal(-1)));
        sqlentry.setPrice(purentry.getPrice());
        sqlentry.setTaxrate(purentry.getTaxrate());
//        sqlentry.setSystaxprice(purentry.getSystaxprice())//系统内含税单价，采购入库没有
        sqlentry.setTaxprice(purentry.getTaxprice());
        sqlentry.setAmount(purentry.getAmount().multiply(new BigDecimal(-1)));
        sqlentry.setTax(purentry.getTax().multiply(new BigDecimal(-1)));
        sqlentry.setTaxamount(purentry.getTaxamount().multiply(new BigDecimal(-1)));
        sqlentry.setIspresent(purentry.getIspresent());
        sqlentry.setRemark(purentry.getRemark());
//        sqlentry.setRefordercode(purentry.getRefordercode());//销售订单号
//        sqlentry.setCustomerOrderNo(purentry.getCustomerOrderNo());//客户订单号
        return sqlentry;
    }
    public OmsSaleissuebill purBillChangeSalBill(OmsPurinwarehsbill pur){
        OmsSaleissuebill sal = new OmsSaleissuebill();
        sal.setBizdate(pur.getBizdate());
        String billNumber = omsTaskUtil.setBillNumber(sal);
        sal.setBillnumber(billNumber);
        //库存组织
        sal.setStorageorgnumber(pur.getStorageorgnumber());
        sal.setStorageorgname(pur.getStorageorgname());
        //设置送货客户
        sal.setCustomernumber(pur.getSuppliernumber());
        sal.setCustomername(pur.getSuppliername());
        //业务类型
        if("110".equals(pur.getBiztypenumber())){
            sal.setBiztypenumber("211");
            sal.setBiztypename("普通销售退货");
        }else if("111".equals(pur.getBiztypenumber())){
            sal.setBiztypenumber("210");
            sal.setBiztypename("普通销售");
        }
        //事务类型
        if("004".equals(pur.getTransactiontypenumber())){
            sal.setTransactiontypenumber("013");
            sal.setTransactiontypename("成本出库退货");
        }else if("005".equals(pur.getTransactiontypenumber())){
            sal.setTransactiontypenumber("012");
            sal.setTransactiontypename("成本出库");
        }
        //记账公司
        sal.setAccountcompanynumber(pur.getAccountcompanynumber());
        sal.setAccountcompanyname(pur.getAccountcompanyname());
        //成本中心
        sal.setCostcenternumber(pur.getCostcenternumber());
        sal.setCostcentername(pur.getCostcentername());
        //币别
        sal.setCurrency(pur.getCurrency());
        //汇率
        sal.setExchangerate(pur.getExchangerate());
        //厂编
//        sal.setFactorymake(pur);
        //来源单据
        sal.setSrcbilltype(pur.getSrcbilltype());
        sal.setSrcbillnumber(pur.getSrcbillnumber());
        //备注
        sal.setDescription(pur.getDescription());
        //创建时间
        sal.setCreatetime(new Date());
        //是否外部客户
        sal.setIsoutcustomer(0L);
        //来源系统
        sal.setSrcsys(pur.getSrcsys());
        return sal;
    }
}
